<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="150px">
      <el-form-item label="短信类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择短信类型" clearable class="!w-240px">
          <el-option
            v-for="dict in useDict('system_sms_template_type')['system_sms_template_type']"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开启状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择开启状态" clearable class="!w-240px">
          <el-option v-for="dict in useDict('common_status')['common_status']" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="模板编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入模板编码" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="短信 API 的模板编号" prop="apiTemplateId">
        <el-input v-model="queryParams.apiTemplateId" placeholder="请输入短信 API 的模板编号" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="短信渠道" prop="channelId">
        <el-select v-model="queryParams.channelId" placeholder="请选择短信渠道" clearable class="!w-240px">
          <el-option
            v-for="channel in channelList"
            :key="channel.id"
            :value="channel.id"
            :label="
              channel.signature +
              `【 ${getDictLabel('system_sms_channel_code', channel.code)}】`
            "
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          style="width: 240px"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="openForm('create')"> <Icon icon="ep:plus" class="mr-5px" />新增 </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"> <Icon icon="ep:download" class="mr-5px" /> 导出 </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="模板编码" align="center" prop="code" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="模板名称" align="center" prop="name" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="模板内容" align="center" prop="content" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="短信类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag type="system_sms_template_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <dict-tag type="common_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="短信 API 的模板编号" align="center" prop="apiTemplateId" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="短信渠道" align="center" width="120">
        <template #default="scope">
          <div>
            {{ channelList.find((channel: any) => channel.id === scope.row.channelId) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" :formatter="dateFormatter" />
      <el-table-column label="操作" align="center" width="210" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)" v-hasPermi="['system:sms-template:update']"> 修改 </el-button>
          <el-button link type="primary" @click="openSendForm(scope.row.id)" v-hasPermi="['system:sms-template:send-sms']"> 测试 </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['system:sms-template:delete']"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SmsTemplateForm ref="formRef" @success="getList" />
  <!-- 表单弹窗：测试发送 -->
  <SmsTemplateSendForm ref="sendFormRef" />
</template>
<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import {
  exportSmsTemplate,
  getSmsTemplatePage,
  deleteSmsTemplate,
  getSimpleSmsChannelList
} from '@/api/system/sms'
import download from '@/utils/download'
import SmsTemplateForm from './SmsTemplateForm.vue'
import SmsTemplateSendForm from './SmsTemplateSendForm.vue'
import { useDict, getDictLabel } from '@/utils/dict'

const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryFormRef = ref() // 搜索的表单
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: null,
  status: null,
  code: '',
  content: '',
  apiTemplateId: '',
  channelId: null,
  createTime: []
})
const exportLoading = ref(false) // 导出的加载中
const channelList = ref([]) // 短信渠道列表
const message = useMessage()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getSmsTemplatePage(queryParams)
    list.value = data?.data?.rows
    total.value = data?.data?.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 发送短信按钮 */
const sendFormRef = ref()
const openSendForm = (id: number) => {
  sendFormRef.value.open(id)
}

/** 删除按钮操作 */
const handleDelete = async (row) => {
  try {
    // 发起删除
    const operIds = row?.id ? [row.id] : []
    await deleteSmsTemplate(operIds)
    // 刷新列表
    await getList()
  } catch {
    message.error('删除失败')
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    // 发起导出
    exportLoading.value = true
    const data = await exportSmsTemplate(queryParams)
    // download.excel(data, '短信模板.xls')
  } catch {
    message.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载渠道列表
  const data = await getSimpleSmsChannelList()
  console.log('getSimpleSmsChannelList',data)
  channelList.value = data.data
})
</script>
